package com.echat.api.demo.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;
import com.thoughtworks.xstream.mapper.CachingMapper;

import java.io.Writer;

/**
 * Created by EChat
 * xml辅助类
 */
public class XMLUtil {

    private static XStream xStream = new XStream(new XppDriver() {
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {

                //节点的class name
                String className = null;

                @SuppressWarnings("unchecked")
                public void startNode(String name, Class clazz) {
                    className = clazz.getName();
                    super.startNode(name, clazz);
                }

                protected void writeText(QuickWriter writer, String text) {
                    if (StringUtil.equals(className, "java.lang.Byte")
                            || StringUtil.equals(className, "java.lang.Short")
                            || StringUtil.equals(className, "java.lang.Integer")
                            || StringUtil.equals(className, "java.lang.Long")) {
                        writer.write(text);
                    } else {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    }
                }
            };
        }
    });

    /**
     * bean转xml字符串
     *
     * @param obj
     * @return
     */
    public static String toXML(Object obj) {
        xStream.alias("xml", obj.getClass());
        return xStream.toXML(obj);
    }

    /**
     * xml字符串转bean
     *
     * @param xml
     * @return
     * @throws Exception
     */
    public static Object toBean(String xml, Class aClass) {
        if (StringUtil.isEmpty(xml)) {
            return null;
        }
        CachingMapper cachingMapper= (CachingMapper) xStream.getMapper();
        cachingMapper.flushCache();
        xStream.alias("xml", aClass);
        return xStream.fromXML(xml);
    }
}
